package com.yeskery.nut.extend.redis;

import redis.clients.jedis.Jedis;

import java.util.function.Function;

/**
 * Jedis执行器，用于处理Redis连接的获取和释放
 * @author YESKERY
 * 2024/9/18
 */
public class JedisExecutor {

    /** Jedis连接池对象 */
    private final JedisConnectionPool jedisConnectionPool;

    /**
     * 构建一个Jedis执行器
     * @param jedisConnectionPool Jedis连接池对象
     */
    public JedisExecutor(JedisConnectionPool jedisConnectionPool) {
        this.jedisConnectionPool = jedisConnectionPool;
    }

    /**
     * 执行一个Jedis操作
     * @param jedisFunction 执行函数
     * @return 执行结果
     * @param <T> 执行函数的返回值类型
     */
    public <T> T execute(Function<Jedis, T> jedisFunction) {
        Jedis jedis = jedisConnectionPool.getCacheConnection();
        try {
            return jedisFunction.apply(jedis);
        } finally {
            jedisConnectionPool.free(jedis);
        }
    }
}
